using GameKit.Core.Context;

namespace GameKitUnity.Core.Context
{
    public static class ContextFrameworkUtils
    {
        public static T GetSystem<T>(this UnityEngine.Component component) where T : ISystem
        {
            return component.TryGetComponent<ISystemContext>(out var systemContext) ? systemContext.GetSystem<T>() : default;
        }

        public static T AddSystem<T>(this UnityEngine.Component component) where T : ISystem
        {
            return component.GetOrAddComponent<SystemContextBehaviour>().Context.AddSystem<T>();
        }

        public static T AddSystem<T>(this UnityEngine.Component component, T system) where T : ISystem
        {
            return component.GetOrAddComponent<SystemContextBehaviour>().Context.AddSystem(system);
        }

        private static T GetOrAddComponent<T>(this UnityEngine.Component component) where T : UnityEngine.Component
        {
            var go = component.gameObject;
            return go.TryGetComponent<T>(out var instance) ? instance : go.AddComponent<T>();
        }
    }
}